import Vue from 'vue';
import {
    url,
} from '@/lib/utils';

import {
    api,
} from '@/lib/api';

import { Module } from 'vuex';
import { RootState } from '@/types/store';
import { stat } from 'fs';

export interface ShopState {
    // 充值余额
    rechargeList:{
        [keyDate: string]: ListWrap<number> & ListReq;
    };
    // 消费记录
    consumeList:{
        [keyDate: string]: ListWrap<number> & ListReq;
    };
    // 充值记录
    // rechargeRecoredList:[];
    rechargeRecoredList: {
        [keyDate: string]: ListWrap<number> & ListReq;
    };
        // 首页产品详情
    productDetail:{
        [productId:number]:Shop.proDetail;
    };

    //
    indexBanners: Framework.Banner[];
     // 商城左侧滑动菜单栏
    sliderList:Framework.sliderList[];

    indexGategory: Framework.IndexGategory[];
    indexRecommendList: Framework.Recommend[];
    shopRecommendListMap: any;
    /** 店铺列表 */
    shopList: {
        [category_sort_search: string]: ListWrap<number> & ListReq;
    };
    bridalShopList: number[];
    allShopList: number[];
    locationDetail:{
        latitude:String,
        longitude:String
    }
    // locationLatitude:number[];
    // locationLongitude:number[];
    shopMap: {
        [shopId: number]: Shop.ListItem;
    };
    shopDetailMap: {
        [shopId: number]: Shop.Detail;
    };
    banners: {
        [shopId: number]: Shop.Banner[];
    };
    /** 精选套系 */
    samples: any;
    /** 购物车信息 */
    cart: {
        [shopId: number]: Shop.CartItem[];
    };
    category: {
        [type: string]: IdName[];
    };
    // 商品服务弹窗 列表
    servierPopupList: {
        [productId: number]: Shop.serviceItem[];
    },
    taoxiservierPopupList: {
        [pkgId: number]: Shop.serviceItem[];
    },
}

const m: Module<ShopState, RootState> = {
    namespaced: true,
    state: {
        // 充值余额
        rechargeList: {},
        consumeList: {},
        // 充值列表
        // rechargeRecoredList: [],
        rechargeRecoredList: {},
        // 首页赠品详情
        productDetail: [],
        //
        indexBanners: [],
        sliderList:[],
        indexGategory: [],
        indexRecommendList: [],
        shopRecommendListMap: {},
        locationDetail:{
            latitude:'',
            longitude:''
        },
        shopList: {},
        bridalShopList: [],
        allShopList: [],
        shopMap: {},
        shopDetailMap: {},
        banners: {},
        /** 精选套系 */
        samples: {},
        /** 购物车信息 */
        cart: {},
        /** 二级类别 */
        category: {},

        // 商品服务弹窗 列表
        servierPopupList: {},
        // 套系服务弹窗 列表
        taoxiservierPopupList: {},
    },

    mutations: {
        // initShopList(state, key) {
        //     Vue.set(state.shopList, key, {
        //         list: [],
        //         loaded: false,
        //         req: false,
        //     });
        // },
        // setShopListReq(state, { key, req }) {
        //     state.shopList[key].req = req;
        // },
        // setShopListLoaded(state, { key, loaded }) {
        //     state.shopList[key].loaded = loaded;
        // },
        // concatShopList(state, { key, list }) {
        //     const ids = [];
        //     list.forEach((item) => {
        //         ids.push(item.id);
        //         Vue.set(state.shopMap, item.id, item);
        //     });
        //     state.shopList[key].list.push(...ids);
        // },
        // 充值余额
        initRechargeList(state, key){
            Vue.set(state.rechargeList, key, {
                list: [],
                loaded: false,
                req: false,
            });
        },
        /**
         * 记录测试分页
         */
        concatRechargeList(state, { key, list }) {
            state.rechargeList[key].list.push(...list);
        },
        /**
         * 测试分页是否全部加载
         */
        setRechargeListLoaded(state, { key, loaded }) {
            state.rechargeList[key].loaded = loaded;
            
        },
        /**
         * 测试分页是否全部加载
         */
        setRechargeListReq(state, { key, req }) {
            state.rechargeList[key].req = req;
            
        },
        // setRechargeList(state,data){
        //     state.rechargeList = data;
        // },
        // 充值记录
        initconsumeList(state, key){
            Vue.set(state.consumeList, key, {
                list: [],
                loaded: false,
                req: false,
            });
        },
        /**
         * 记录测试分页
         */
        concatconsumeList(state, { key, list }) {
            state.consumeList[key].list.push(...list);
        },
        /**
         * 测试分页是否全部加载
         */
        setconsumeListLoaded(state, { key, loaded }) {
            state.consumeList[key].loaded = loaded;
            
        },
        /**
         * 测试分页是否全部加载
         */
        setconsumeListReq(state, { key, req }) {
            state.consumeList[key].req = req;
            
        },

        // 
        // 设置充值记录
        // setrechargeRecoredList(state,data){
        //     state.rechargeRecoredList = data;
        // },
        // 测试分页
        initrechargeRecoredList(state, key){
            Vue.set(state.rechargeRecoredList, key, {
                list: [],
                loaded: false,
                req: false,
            });
        },
        /**
         * 记录测试分页
         */
        concatrechargeRecoredList(state, { key, list }) {
            state.rechargeRecoredList[key].list.push(...list);
        },
        /**
         * 测试分页是否全部加载
         */
        setrechargeRecoredListLoaded(state, { key, loaded }) {
            state.rechargeRecoredList[key].loaded = loaded;
        },
        /**
         * 测试分页是否全部加载
         */
        setrechargeRecoredListReq(state, { key, req }) {
            state.rechargeRecoredList[key].req = req;
        },
        // 设置首页评论详情
        setProductDetail(state,data){
            state.productDetail = data;
        },

        /**
         * 设置首页banner
         */
        setIndexBanners(state, list) {
            state.indexBanners = list;
        },

        /**
         * 设置首页分类
         */
        setIndexGategory(state, list) {
            state.indexGategory = list;
        },
        /**
         * 设置首页推荐
         */
        setIndexRecommendList(state, list) {
            state.indexRecommendList = list;
        },
        /**
         * 设置店铺推荐
         */
        setShopRecommendList(state, { shopId, list }) {
            Vue.set(state.shopRecommendListMap, shopId, list);
        },
        /**
         * 设置婚纱摄影门店列表
         */
        setBridalShopList(state, list) {
            const idList = [];
            list.forEach((item) => {
                idList.push(item.id);
                Vue.set(state.shopMap, item.id, item);
            });
            state.bridalShopList = idList;
        },
        setAllShopList(state, list) {
            const idList = [];
            list.forEach((item) => {
                idList.push(item.id);
                Vue.set(state.shopMap, item.id, item);
            });
            state.allShopList = idList;
        },
        setgetLocation(state,data){
            state.locationDetail.latitude = data.latitude;
            state.locationDetail.longitude = data.longitude;
        },
        initShopList(state, key) {
            Vue.set(state.shopList, key, {
                list: [],
                loaded: false,
                req: false,
            });
        },
        setShopListReq(state, { key, req }) {
            state.shopList[key].req = req;
        },
        setShopListLoaded(state, { key, loaded }) {
            state.shopList[key].loaded = loaded;
        },
        // concatShopList(state, { key, list }) {
        //     const ids = [];
        //     list.forEach((item) => {
        //         ids.push(item.id);
        //         Vue.set(state.shopMap, item.id, item);
        //     });
        //     state.shopList[key].list.push(...ids);
        // },
        // 修改
        concatShopList(state, { key, list, isSwitchTab }) {
			// if (state.productList[key]) {
			let idList = state.shopList[key].list;

			if (list.length) {
				list.forEach((item) => {
					idList.push(item.id);
					Vue.set(state.shopMap, item.id, item);
				});
				Vue.set(state.shopList[key], "list", idList);
			}
			// // 边界条件处理，如果请求的商品列表为空

            	// 如果请求列表为空，但不是上拉加载，而是切换新的分类tab后请求
			if (isSwitchTab && !state.shopList[key].list.length) {
				idList = [];
				state.shopMap = {};
				Vue.set(state.shopList[key], "list", []);
                // Vue.set(state.productMap, item.id, {});
            }

		},

        setShopDetail(state, { id, detail }) {
            Vue.set(state.shopDetailMap, id, detail);
        },
        /**
         * 记录banners
         */
        setBanners(state, { shopId, banners }) {
            Vue.set(state.banners, shopId, banners);
        },
        // 分类
        getSliderList(state, data){
            state.sliderList = data;
        },
        /**
         * 记录精选套系
         */
        setSamples(state, { shopId, samples }) {
            Vue.set(state.samples, shopId, samples);
        },
        /**
         * 记录购物车信息
         */
        setCart(state, { cart }) {
            state.cart = cart;
        },
        /**
         * 记录category
         */
        setCategory(state, { type, list }) {
            Vue.set(state.category, type, list);
        },
        // 存储商城服务弹窗列表数据
        setServierPopupList(state, { key, list, }){
            // state.servierPopupList = list;
            Vue.set(state.servierPopupList, key, list);
        },
        setTaoxiServierPopupList(state, { key, list, }){
            Vue.set(state.taoxiservierPopupList, key, list);
        }
    },

    actions: {
        // 充值余额
        async getRechargeList({ state,commit },{ offset, count,forceUpdate }){
            // if(state.rechargeList.length > 0 && !forceUpdate){
            //     return;
            // }
            // const res = await api.get({
            //     url:`${url}/api/user/balance`,
            //     data:{
            //         offset: offset,
            //         count: count
            //     }
            // });
            // if(res.statusCode === 200 && res.data.status === 0){
            //     commit('setRechargeList',res.data.data);
            // }
            const key = null;
            if(!state.rechargeList[key] || forceUpdate){
                commit('initRechargeList', key);
            }
            const wrap = state.rechargeList[key];
            if (wrap.loaded || wrap.req) {
                return;
            }
            const end = offset + count;
            const length = wrap.list.length;
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - offset;
            }
            commit('setRechargeListReq', { key, req: true });
            const res = await api.get({
                url: `${url}/api/user/balance`,
                data:{
                    offset: offset,
                    count: count,
                }
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatRechargeList', {
                    key,
                    list,
                });
                if (list.length < count) {
                    commit('setRechargeListLoaded', { key, loaded: true });
                }
            }
            commit('setRechargeListReq', { key, req: false });
            return res;
        },
        // 消费记录
        async getconsumeList({ state,commit }, {offset, count, forceUpdate }){
            // if(state.consumeList.length > 0 && !forceUpdate){
            //     return;
            // }
            // const res = await api.get({
            //     url:`${url}/api/user/consume`,
            //     data:{
            //         offset: offset,
            //         count: count
            //     }
            // });
            // if(res.statusCode === 200 && res.data.status === 0){
            //     commit('setconsumeList',res.data.data);
            // }

            const key = null;
            if(!state.consumeList[key] || forceUpdate){
                commit('initconsumeList', key);
            }
            const wrap = state.consumeList[key];
            if (wrap.loaded || wrap.req) {
                return;
            }
            const end = offset + count;
            const length = wrap.list.length;
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - offset;
            }
            commit('setconsumeListReq', { key, req: true });
            const res = await api.get({
                url: `${url}/api/user/consume`,
                data:{
                    offset: offset,
                    count: count,
                }
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatconsumeList', {
                    key,
                    list,
                });
                if (list.length < count) {
                    commit('setconsumeListLoaded', { key, loaded: true });
                }
            }
            commit('setconsumeListReq', { key, req: false });
            return res;
        },
        // 充值记录
        async getrechargeRecoredList({ state , commit }, { offset, count, forceUpdate}){
            // 尝试做分页请求
            const key = null;
            if(!state.rechargeRecoredList[key] || forceUpdate){
                commit('initrechargeRecoredList', key);
            }
            const wrap = state.rechargeRecoredList[key];
            if (wrap.loaded || wrap.req) {
                return;
            }
            const end = offset + count;
            const length = wrap.list.length;
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - offset;
            }
            commit('setrechargeRecoredListReq', { key, req: true });

            const res = await api.get({
                url: `${url}/api/user/recharge`,
                data:{
                    offset: offset,
                    count: count,
                }
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatrechargeRecoredList', {
                    key,
                    list,
                });
                if (list.length < count) {
                    commit('setrechargeRecoredListLoaded', { key, loaded: true });
                }
            }
            commit('setrechargeRecoredListReq', { key, req: false });
            return res;

            // 原请求方法 备份
            // if(state.rechargeRecoredList.length > 0 && !forceUpdate){
            //     return;
            // }
            // const res = await api.get({
            //     url: `${url}/api/user/recharge`,
            //     data:{
            //         offset: offset,
            //         count: count,
            //     }
            // });
            // if (res.statusCode === 200 && res.data.status === 0) {
            //     commit('setrechargeRecoredList', res.data.data);
            // }
            // return res;
        },

        async getProductDetail({ state,commit }, { productId,forceUpdate }){
            // if (state.productDetail[productId] && !forceUpdate) {
            //     return;
            // }
            const res = await api.get({
                url: `${url}/api/package/giftinfo`,
                data:{
                    id: productId
                }
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setProductDetail', res.data.data);
            }
            return res;
        },


        /**
         * 获取首页banner
         */
        async getIndexBanners({ state, commit }, forceUpdate) {
            if (state.indexBanners.length > 0 && !forceUpdate) {
                return;
            }
            const res = await api.get({
                url: `${url}/api/banner`,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setIndexBanners', res.data.data);
            }
            return res;
        },
        /**
         * 获取商城左滑菜单
         */
        async getSliderList({ state, commit }, { pid, is_view_show }) {
            const key = `${pid}_${is_view_show}`;
            const response = await api.get({
                url: `${url}/api/category`,
                data: {
                    pid: pid,
                    is_view_show: is_view_show,
                },
            });
            const rdata = response.data;
            if (response.statusCode === 200 && rdata.status === 0) {
                var all = {id: '-1', name: "全部商家"};
                var _data = rdata.data.push(all)
                commit('getSliderList',rdata.data);
            }
            return rdata;
        },
        /**
         * 获取首页分类
         */
        async getIndexGategory({ state, commit }, forceUpdate) {
            if (state.indexGategory.length > 0 && !forceUpdate) {
                return;
            }
            const res = await api.get({
                url: `${url}/api/category`,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setIndexGategory', res.data.data);
            }
            return res;
        },

        /**
         * 获取首页推荐列表
         */
        async getIndexRecommendList({ state, commit }, forceUpdate) {
            if (state.indexRecommendList.length > 0 && !forceUpdate) {
                return;
            }
            const res = await api.get({
                url: `${url}/api/recommend`,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setIndexRecommendList', res.data.data);
            }
            return res;
        },
        /**
         * 获取店铺推荐列表
         */
        async getShopRecommendList({ state, commit }, { shopId, forceUpdate }) {
            if (state.shopRecommendListMap[shopId] && !forceUpdate) {
                return;
            }
            const res = await api.get({
                url: `${url}/api/shop/recommend`,
                data: {
                    shop_id: shopId,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setShopRecommendList', { shopId, list: res.data.data });
            }
            return res;
        },
        async getLocation({ state, commit },forceUpdate){
            wx.getLocation({
                type: 'wgs84',
                success: function (success) {
                    const latitude= success.latitude;
                    const longitude= success.longitude;
                    commit('setgetLocation', success);
                    // this.getShopList();
                }
            });
        },
        /**
         * 获取店铺列表(门店)
         */
        async getShopList({ state, commit }, { offset, count, category = null, sort = null, search = null, forceUpdate = false ,isSwitchTab, }) {

            const key = `_${sort}_${search}`; //${category}

            //  新增：如果切换了分类 初始化数据
			if (isSwitchTab) {
				commit("initShopList", key);
			}

            if (!state.shopList[key] || (offset === 0 && forceUpdate)) {
                commit('initShopList', key);
            }

            // if (forceUpdate || !state.shopList[key]) {
            //     commit('initShopList', key);
            // }

            const wrap = state.shopList[key];
            const length = wrap.list.length;
            const end = offset + count;
            if (wrap.loaded || wrap.req) {
                return;
            }
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - length;
            }

            commit('setShopListReq', { key, req: true });

            const data: any = {
                offset: isSwitchTab ? 0 : offset,
                count
            };
            if (category) {
                if (category === '婚纱摄影') {
                    data.is_photography = 1;
                } else {
                    data.category = category;
                }
            }
            if (sort) {
                data.sort = sort;
            }
            if (search) {
                data.search = search;
            }
            data.latitude = state.locationDetail.latitude;
            data.longitude = state.locationDetail.longitude;

            const res = await api.get({
                url: `${url}/api/shop`,
                data,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatShopList', {
                    key,
                    list,
                    // 新增
					isSwitchTab,
                });
                if (list.length < count) {
                    commit('setShopListLoaded', { key, loaded: true });
                }
            }
            commit('setShopListReq', { key, req: false });
            return res;


        },
        // async getShopList({ state, commit }, { offset, count, category, sort, search, forceUpdate = true }) {

        //     const key = `${category}_${sort}_${search}`;

        //     if (forceUpdate || !state.shopList[key]) {
        //         commit('initShopList', key);
        //     }
        //     const wrap = state.shopList[key];
        //     const length = wrap.list.length;
        //     const end = offset + count;
        //     if (wrap.loaded || wrap.req) {
        //         return;
        //     }
        //     if (end <= length) {
        //         return;
        //     }
        //     if (offset < length) {
        //         offset = length;
        //         count = end - length;
        //     }
        //     // commit('setShopListReq', { key, req: true });
        //     const data: any = {
        //         offset,
        //         count
        //     };
        //     if (category) {
        //         if (category === '婚纱摄影') {
        //             data.is_photography = 1;
        //         } else {
        //             data.category = category;
        //         }
        //     }
        //     if (sort) {
        //         data.sort = sort;
        //     }
        //     if (search) {
        //         data.search = search;
        //     }
        //     data.latitude = state.locationDetail.latitude;
        //     data.longitude = state.locationDetail.longitude;

        //     const res = await api.get({
        //         url: `${url}/api/shop`,
        //         data,
        //     });
        //     console.log('请求门店列表：',res.data)
        //     if (res.statusCode === 200 && res.data.status === 0) {
        //         const list = res.data.data;
        //         commit('concatShopList', { key, list });
        //         if (list.length < count) {
        //             commit('setShopListLoaded', { key, loaded: true });
        //         }
        //     }
        //     commit('setShopListReq', { key, req: false });
        //     return res;


        // },
        /**
         * 获取婚纱店铺列表
         */
        async getBridalShopList({ state, commit }, forceUpdate) {
            if (!forceUpdate && state.bridalShopList.length) {
                return;
            }
            const res = await api.get({
                url: `${url}/api/shop`,
                data: {
                    offset: 0,
                    count: 100, // tip: 针对第二个tab进行处理
                    is_photography: 1,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setBridalShopList', res.data.data);
            }
            return res;
        },
        /**
         * 获取所有店铺列表
         */
        async getAllShopList({ state, commit }, forceUpdate) {
            if (!forceUpdate && state.allShopList.length) {
                return;
            }
            const res = await api.get({
                url: `${url}/api/shop`,
                data: {
                    offset: 0,
                    count: 1000, // tip: 获取所有
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setAllShopList', res.data.data);
            }
            return res;
        },
        /**
         * 获取店铺详情
         */
        async getShopDetail({ state, commit }, { shopId, forceUpdate = false }) {
            if (!forceUpdate && state.shopDetailMap[shopId]) {
                return;
            }
            const res = await api.get({
                url: `${url}/api/shop/detail`,
                data: {
                    id: shopId,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setShopDetail', {
                    id: shopId,
                    detail: res.data.data,
                });
            }
            return res;
        },
        /**
         * 获取门店banner
         */
        async getBanners({ state, commit }, { shopId, forceUpdate = false }) {
            if (!forceUpdate && state.banners[shopId]) {
                return;
            }
            const res = await api.get({
                url: `${url}/api/shop/banner`,
                data: {
                    shop_id: shopId,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setBanners', {
                    shopId,
                    banners: res.data.data,
                });
            }
            return res;
        },
        /**
         * 获得套系精选
         */
        async getSamples(context, { shopId }) {
            const res = await api.get({
                url: `${url}/api/shop/sample`,
                data: {
                    shop_id: shopId,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                context.commit('setSamples', {
                    shopId,
                    samples: res.data.data,
                });
            }
            return res;
        },
        /**
         * 获取购物车
         */
        async getCart(context, { forceUpdate }) {
            if (Object.keys(context.state.cart).length && !forceUpdate) {
                return;
            }
            const res = await api.get({
                url: `${url}/api/good/shopping_cart`,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                context.commit('setCart', {
                    cart: res.data.data && !Array.isArray(res.data.data) ? res.data.data : {},
                });
            }
            return res;
        },
        /**
         * 更新购物车
         */
        async updateCart(context, { cart }) {
            const res = await api.post({
                url: `${url}/api/good/shopping_cart`,
                data: {
                    data: cart,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                await context.dispatch('getCart', {
                    forceUpdate: true,
                });
            }
            return res;
        },
        async getCategory(context, { type }) {
            const res = await api.get({
                url: `${url}/api/shop/category`,
                data: {
                    type,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                context.commit('setCategory', {
                    type,
                    list: res.data.data,
                });
            }
            return res;
        },
        /**
         * 获取商品服务弹窗列表
         */
        async getServierPopupList(context, { id, forceUpdate }) {
            const res = await api.get({
                url: `${url}/api/good/tag`,
                data: {
                    id
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                context.commit('setServierPopupList', {
                    key: id + '_',
                    list: res.data.data,
                });
            }
            return res;
        },
        /**
         * 获取套系服务弹窗列表
         */
        async getTaoxiServierPopupList(context, { id, forceUpdate }) {
            const res = await api.get({
                url: `${url}/api/package/tag`,
                data: {
                    id
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                context.commit('setTaoxiServierPopupList', {
                    key: id + '_',
                    list: res.data.data,
                });
            }
            return res;
        },
    },
};

export default m;
